package howl.Servlets.cron;

import howl.Twitter.TwitterProvider;
import howl.model.Handler;
import howl.model.Model;
import howl.types.HowlUser;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import compiler.HowlCompiler;
import compiler.HowlToken;
import compiler.exceptions.HowlModelException;
import compiler.exceptions.HowlParserException;
import compiler.exceptions.HowlUnauthorisedAction;

import twitter4j.DirectMessage;
import twitter4j.Twitter;
import twitter4j.TwitterException;

@SuppressWarnings("serial")
public class RetrieveTwitterData extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");

		Twitter t = new Twitter("UoWHowl", "wolverhampton");
		HowlCompiler hc = new HowlCompiler();
		List<DirectMessage> l;
		List<HowlToken> hts;
		try {
			l = t.getDirectMessages();
			HowlUser hu;
			Handler handler;
			for (int i = 0; i < l.size(); i++) {
				hu = Model.getHowlUserfromTwitterName(l.get(i).getSender()
						.getScreenName());

				if (hu != null) {
					handler = new Handler(hu);
					try {
						hts = hc.parse(l.get(i).getText());
						handler.Handle(hts);
					} catch (HowlParserException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (HowlUnauthorisedAction e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (HowlModelException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					t.destroyDirectMessage(l.get(i).getId());

				} else {

				}
			}
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
